﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Text;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;

namespace MobileBroadbandLoggingMonitor.Web
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            StringBuilder formValues = new StringBuilder();
            foreach (string key in this.Request.Form.AllKeys)
            {
                formValues.Append(string.Format("Name:{0}\nValue:\n{1}\n\n\n", key, this.Request.Form[key]));
            }
            

            TextWriter myTextWriter = new StringWriter();
            HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter);

            FormattedMail formattedMail = (FormattedMail) LoadControl("FormattedMail.ascx");
            formattedMail.FormData = formValues.ToString();
            formattedMail.RenderControl(myWriter);

            string thedata = myTextWriter.ToString();
            SendMessage("christer.dk@gmail.com", myTextWriter.ToString());
            WriteToFile(thedata);
            string email = this.Request.Form["email"];
            if (!string.IsNullOrEmpty(email))
            {
                SendMessage(email, thedata); 
            }
        }

        private void WriteToFile(string thedata)
        {
            string file = Server.MapPath("received") + @"\" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + Session.SessionID + ".html";
            try
            {
                File.WriteAllText(file, thedata);
            }
            catch (Exception ex)
            {
                throw new Exception(file, ex);
            }
        }

        private void SendMessage(string receiver, string mailcontent)
        {
            MailMessage mail = new MailMessage("info@mobilebroadbanduser.eu", receiver);
            mail.IsBodyHtml = true;
            mail.Body = mailcontent;
            mail.Subject = "Your copy of shared information";
            SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["smtpserver"]);
            smtpClient.Send(mail);
        }
    }
}
